import os
import sys

from robot.api import logger
from robot.utils.robotpath import get_link_path
from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError

from ..exception.TestException import TestException
from ..exception.errorcode import ErrorCode

PY2 = sys.version_info < (3,)


def capture_page_screenshot(driver, filename='screenshot/zcm-screenshot-{index}.png'):
    """
    仿照SeleniumLibrary/keywords/screenshot.py
    不支持设置文件夹
    """
    if not driver:
        logger.info('Cannot capture screenshot because no browser is open.')
        return
    if os.environ.get("PABOT_COMMAND"):
        filename = os.path.basename(filename)
    path = _get_screenshot_path(filename)
    _create_directory(path)
    if not driver.save_screenshot(path):
        raise TestException.by_error_code(ErrorCode.SAVE_SCREENSHOT_ERROR, value=path)
    _embed_to_log(path, 800)
    return path

def save_html_file(driver, filename='zcm-html-{index}.html'):
    if not driver:
        logger.info('Cannot capture screenshot because no browser is open.')
        return
    path = _get_screenshot_path(filename)
    _create_directory(path)
    with open(path, "w+", encoding='utf-8') as f:
        f.write(driver.page_source)
    return path

def _get_screenshot_path(filename):
    directory = _log_dir()
    filename = filename.replace('/', os.sep)
    index = 0
    while True:
        index += 1
        formatted = _format_path(filename, index)
        path = os.path.join(directory, formatted)
        # filename didn't contain {index} or unique path was found
        if formatted == filename or not os.path.exists(path):
            return path

def _format_path(file_path, index):
    if PY2:
        import string
        return string.Formatter().vformat(file_path, (), _SafeFormatter(index=index))
    return file_path.format_map(_SafeFormatter(index=index))

def _create_directory(path):
    target_dir = os.path.dirname(path)
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

def _log_dir():
    try:
        logfile = BuiltIn().get_variable_value('${LOG FILE}')
        if logfile == 'NONE':
            return BuiltIn().get_variable_value('${OUTPUTDIR}')
        return os.path.dirname(logfile)
    except RobotNotRunningError:
        return os.getcwdu() if PY2 else os.getcwd()

# def _log_dir():
#     try:
#         logfile = BuiltIn().get_variable_value('${LOG FILE}')
#         if logfile == 'NONE':
#             dir_path = BuiltIn().get_variable_value('${OUTPUTDIR}')
#         else:
#             dir_path = os.path.dirname(logfile)
#         if os.environ.get("PABOT_COMMAND"):
#             split_str = os.sep + "pabot_results"
#             dir_split_list = dir_path.split(split_str)
#             dir_path = dir_split_list[0]
#         return dir_path
#     except RobotNotRunningError:
#         return os.getcwdu() if PY2 else os.getcwd()


def _embed_to_log(path, width):
    # Image is shown on its own row and thus previous row is closed on
    # purpose. Depending on Robot's log structure is a bit risky.
    logger.info('</td></tr><tr><td colspan="3">'
              '<a href="{src}"><img src="{src}" width="{width}px"></a>'
              .format(src=get_link_path(path, _log_dir()), width=width), html=True)


class _SafeFormatter(dict):

    def __missing__(self, key):
        return '{%s}' % key